<script setup>
import powerSet from './power-set.js'
// import { defineEmits } from 'vue';
const emit = defineEmits(['change']) // 声明事件不能在函数内

    const goodsAPI = defineProps({
        goods: {
            type: Object,
            default: () => {
                return {}
            }
        }
    })
    
    const goods = goodsAPI.goods
    // console.log(goods);
    let pathMap = getPathMap(goods)
    console.log(pathMap);
    initDisabledStatus(goods.specs, pathMap)
// // 导出函数
// defineExpose({getPathMap, initDisabledStatus})

        

    

    // 一：切换选中状态
    // 核心思路：1. 如果当前已经激活，就取消激活
    // 2. 如果当前未激活，就把自己和同排的其他规格取消激活，再把自己激活
    function changeSelectedStatus(item, val) {
        if (val.disabled) return
        // item: 同一排对象 val: 当前点击项
        // console.log(item, val);
        if (val.selected) {
            val.selected = false
        } else {
            item.values.forEach(item => {
                item.selected = false
            })
            val.selected = true
        }
        
        updateDisabledStatus(goods.specs, pathMap)
    //     // 产出SKU对象数据
       const index = getSelectedValues(goods.specs).findIndex(item => item === undefined)
        if (index > -1) {
            console.log('找到undefined, 信息不完整');
            emit('change', {})
        } else {
            console.log('没有找到undefined, 信息完整，可以产出');
            // 获取sku对象
           const key = getSelectedValues(goods.specs).join('-')
            const skuIds = pathMap[key]
            console.log(skuIds);
            // 以skuId作为匹配项，去goods.value.skus数组中找
           const skuObj = goods.skus.find(item => item.id === skuIds[0])
            console.log('sku对象为', skuObj);
           
           emit('change', {
            skuId: skuObj.id,
            inventory: skuObj.inventory,
            oldPrice: skuObj.oldPrice,
            price: skuObj.price,
            specsText: skuObj.specs.map(item => {
                return `${item.name}：${item.valueName}`
            }).join(' ')
           })

        }
    }

    // 二：生成有效路径字典对象
    function getPathMap(goods) {
        const pathMap = {}
        // 1. 根据数据skus字段筛选有效的sku数组
        const effectiveSkus = goods.skus.filter(item => item.inventory > 0)
        // console.log(effectiveSkus);
        // 2. 根据有效的sku使用算法 （子集算法）[1, 2] => [[1], [2], [1, 2]]
        effectiveSkus.forEach(sku => {
            // 2.1 获取匹配的valueName组成的数组
            const selectedValArr = sku.specs.map(val => val.valueName)
            // console.log(selectedValArr);
            // 2.2 使用算法获取子集
           const valueArrPowerSet = powerSet(selectedValArr)
        //    console.log(valueArrPowerSet);
            // 3. 把得到的子集生成最终的路径字典对象
            valueArrPowerSet.forEach(arr => {
                // 初始化key 数组join -> 字符串 对象的key
                const key = arr.join('-') // join把数组转换成字符串
                // 如果已经存在当前key了，就往数组中直接添加skuId 不存在key 直接赋值
                if (pathMap[key]) {
                    pathMap[key].push(sku.id)
                } else {
                    pathMap[key] = [sku.id]
                }
            })
            
        })
        return pathMap
    }

    

    // 三 ：初始化禁用状态
    function initDisabledStatus(specs, pathMap) {
        specs.forEach(spec => {
            spec.values.forEach(val => {
                if (pathMap[val.name]) {
                    val.disabled = false
                } else {
                    val.disabled = true
                }
            })
        })
    }

    // 获取选中项的数组
    function getSelectedValues(specs) {
        const arr = []
        specs.forEach(spec => {
            // 目标：找到values中selected为true的项，然后把它的name字段添加到数组对应的位置
            const selectedVal = spec.values.find(item => item.selected)
            arr.push(selectedVal ? selectedVal.name : undefined)
            
        })
        return arr
    }

    // 四：切换时更新禁用状态
    function updateDisabledStatus(specs, pathMap) {
        specs.forEach((spec, index) => {
            const selectedValues = getSelectedValues(specs)
            console.log(selectedValues);
            console.log('wai'); 
            spec.values.forEach(val => {
                selectedValues[index] = val.name
                console.log(selectedValues); 
                const key = selectedValues.filter(value => value).join('-')
                if (pathMap[key]) { 
                    val.disabled = false
                } else {
                    val.disabled  = true
                }
            })
            console.log('---------');
        })
    }
</script>


<template>
    <div class="goods-sku">
        <dl v-for="item in goods.specs" :key="item.id">
            <dt>{{ item.name }}</dt>
            <dd>
                <template v-for="val in item.values" :key="val.name">
                    <!-- 图片 -->
                    <img v-if="val.picture" :class="{selected: val.selected, disabled: val.disabled}" @click="changeSelectedStatus(item, val)" :src="val.picture" alt="">
                    <!-- 文字 -->
                    <span v-else :class="{selected: val.selected, disabled: val.disabled}" @click="changeSelectedStatus(item, val)">{{ val.name }}</span>
                </template>
            </dd>
        </dl>
    </div>
</template>


<style scoped lang='scss'>
// @import "@/styles/var.scss"; // 提示已弃用
    @mixin sku-state-mixin {
        border: 1px solid #e4e4e4;
        margin-right: 10px;
        cursor: pointer;

        &.selected {
            border-color: $xtxColor;
        }

        &.disabled {
            opacity: 0.6;
            border-style: dashed;
            cursor: not-allowed;
        }
        }

        .goods-sku {
        padding-left: 10px;
        padding-top: 20px;

        dl {
            display: flex;
            padding-bottom: 20px;
            align-items: center;

            dt {
            width: 50px;
            color: #999;
            }

            dd {
            flex: 1;
            color: #666;

            >img {
                width: 50px;
                height: 50px;
                margin-bottom: 4px;
                @include sku-state-mixin;
            }

            >span {
                display: inline-block;
                height: 30px;
                line-height: 28px;
                padding: 0 20px;
                margin-bottom: 4px;
                @include sku-state-mixin;
            }
            }
        }
    }
</style>